1
/******************************** Module Header ********************************\
2 Module Name: Program.cs
3 Project: CSHeapCorruption
4 Copyright (c) Microsoft Corporation.
8 This source is subject to the Microsoft Public License.
9 See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
10 All other rights reserved.
12 THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
13 EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES
14 OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
15 \*******************************************************************************/
18 using System
.Runtime
.InteropServices
;
21 namespace CSHeapCorruption
25 static void Main(string[] args
)
27 if (args
.Length
> 0 && (args
[0].StartsWith("-") || args
[0].StartsWith("/")))
29 string cmd
= args
[0].Substring(1);
31 if (String
.Compare(cmd
, "o", true) == 0)
33 // Overrun the managed GC heap.
34 OverrunManagedGCHeap();
36 else if (String
.Compare(cmd
, "h", true) == 0)
38 // Mismatch the heap handle.
51 Console
.Write("Press ENTER to exit ...");
56 static void PrintInstructions()
58 Console
.WriteLine("CSHeapCorruption Instructions:");
59 Console
.WriteLine("-o Overrun the managed GC heap");
60 Console
.WriteLine("-h Mismatch the heap handle");
64 #region Managed GC Heap Overrun
69 static void OverrunManagedGCHeap()
71 int[] buffer
= new int[50];
72 for (int i
= 0; i
< buffer
.Length
; i
++)
77 Console
.Write("Press ENTER to overrun GC heap ...");
80 InitializeBuffer(buffer
, buffer
.Length
);
85 [DllImport("CSHeapCorruption.NativeDll.dll", CharSet
= CharSet
.Unicode
)]
86 static extern void InitializeBuffer(int[] buffer
, int size
);
91 #region Heap Handle Mismatch
96 static void MismatchHeapHandle()
98 // Allocate a block of memory. The native function AllocateMemory
99 // allocates the memory on the CRT heap.
100 IntPtr pMem
= AllocateMemory(50);
102 Console
.Write("Press ENTER to mismatch heap handle ...");
105 // Free the allocated memory on the wrong process heap.
106 Marshal
.FreeHGlobal(pMem
);
109 [DllImport("CSHeapCorruption.NativeDll.dll", CharSet
= CharSet
.Unicode
)]
110 static extern IntPtr
AllocateMemory(int bytes
);